package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.dto.ExcelDictDTO;
import com.atguigu.srb.core.mapper.DictMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuying
 * @date 2022/11/7
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    private List<ExcelDictDTO> list = new ArrayList<>();

    private static final int COUNT = 5;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条记录: {}", data);

        //每五条数据存入到list集合中
        list.add(data);
        if (list.size() >= COUNT) {
            //当数据达到五条时，调用mapper层方法存入到数据库
            savaData();
            //存入之后重新清空list集合中的数据
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //最后有数据不满五条时，最终一次性存储剩余数据
        savaData();

        log.info("所有数据解析完成");
    }

    public void savaData() {
        log.info("{} 多少条数据被存到数据库...",list.size());
        //调用mapper层的save方法：save list对象
        dictMapper.insertBatch(list);
        log.info("{} 条数据被成功存储到数据库！",list.size());
    }
}
